package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * impl 服务
 *
 * @author DiXiaoNie
 * @date 2022/12/21
 * @since 2022/12/21 16:29
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 查找列表
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        if (dto.getIsCollection() == null) {
            dto.setIsCollection((short) 0);
        }

        //2.分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper();
        //是否收藏
        queryWrapper.eq(dto.getIsCollection() == 1, WmMaterial::getIsCollection, dto.getIsCollection())
                //按照用户查询
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getWmUserThreadLocal().getId())
                //按照时间倒序
                .orderByDesc(WmMaterial::getCreatedTime);
        page = page(page, queryWrapper);

        //3.结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 取消收藏
     *
     * @param id id 图片id
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    public ResponseResult unCollect(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(WemediaConstants.CANCEL_COLLECT_MATERIAL);
        boolean state = this.updateById(wmMaterial);

        return state ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)
                : ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID.getCode(), "操作失败");
    }

    /**
     * 收藏
     *
     * @param id id 图片id
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    public ResponseResult collect(Integer id) {
        //判断前端传来的数据是否为空
        if (id == null) {
            //为空返回数据错误
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //设置需要更新的值
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(WemediaConstants.COLLECT_MATERIAL);
        boolean state = this.updateById(wmMaterial);
        //判断更新后的数据状态  为true返回操作成功  为false返回操作失败
        return state ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)
                : ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID.getCode(), "操作失败");

    }

    /**
     * 删除图片
     *
     * @param id id 图片id
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteImage(Integer id) {
        //判断前端传来的数据是否为空
        if (id == null) {
            //为空直接返回数据错误
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询表中是否存在materId为id的值的数据
        Integer wmNewsMaterialCount = this.wmNewsMaterialService
                .count(Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, id));
        //为空说明数据错误直接返回
        if (wmNewsMaterialCount == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //查回的数据大于0说明该图片已被绑定 不可被删除
        if (wmNewsMaterialCount > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID.getCode(), "图片不可删除");
        }
        //根据前端传来的数据到表中查到符合该id的数据
        WmMaterial wmMaterial = this.getById(id);
        //为空说明数据不存在直接返回
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除图片记录
        boolean state = this.removeById(id);
        //判断图片是否删除成功
        if (!state) {
            //若删除失败执行以下返回值
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID.getCode(), "删除失败");
        }
        //删除成功后把minio中的图片一并删除
        this.fileStorageService.delete(wmMaterial.getUrl());
        //返回删除成功
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }


    /**
     * 上传图片
     *
     * @param file 文件
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    public ResponseResult uploadImage(MultipartFile file) {
        try {
            //数据校验
            if (file == null || file.getSize() == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //1.获取图片的后缀名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            //2.重新定义上传图片的名称 保证名称唯一
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;

            //3.执行上传图片到minio中 返回一个地址
            String path = fileStorageService.uploadImgFile("", newFileName, file.getInputStream());

            //4.保存数据到wm_material表中
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(WmThreadLocalUtil.getWmUserThreadLocal().getId());
            wmMaterial.setUrl(path);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
            //5.返回数据
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
